package com.tenbent.product.base.core;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.tenbent.product.base.filter.MyFilter;
import com.tenbent.product.base.servlet.MyServlet;
import org.springframework.web.WebApplicationInitializer;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * 配置自定义 filter servlet
 *
 * 通过配置 WebStatFilter ,StatViewServlet 开启 dataSource 监控
 *
 * 入口地址为： http://localhost:8080/druid/index.html
 *
 * @author Randy
 *
 *         Created by ThinkPad on 2017/7/24.
 */
public class MyServletWebApplicationInitializer implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {

		/** 自定义filter **/
		MyFilter myFilter = new MyFilter("/myServlet/fail");
		FilterRegistration.Dynamic reginFilter = servletContext.addFilter("myFilter", myFilter);
		reginFilter.addMappingForUrlPatterns(null, false, MyServlet.MAPPING);

		/** 阿里数据源监控过滤器 **/
		WebStatFilter druidWebStatFilter = new WebStatFilter();
		FilterRegistration.Dynamic druidReginFilter = servletContext.addFilter("druidWebStatFilter",
				druidWebStatFilter);
		druidReginFilter.addMappingForUrlPatterns(null, false, "/*");
		druidReginFilter.setInitParameter(WebStatFilter.PARAM_NAME_EXCLUSIONS,
				"*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");

		/** 注册MyServlet到容器并且只处理 myServlet mapping的请求 **/
		ServletRegistration.Dynamic reginServlet = servletContext.addServlet("myServlet", MyServlet.class);
		reginServlet.addMapping(MyServlet.MAPPING);

		/** 注册监控 Druid数据源 servlet 用于方位监控界面 **/
		ServletRegistration.Dynamic statViewServlet = servletContext.addServlet("statViewServlet",
				new StatViewServlet());
		statViewServlet.addMapping("/druid/*");
		/** ip白名单 **/
		statViewServlet.setInitParameter(StatViewServlet.PARAM_NAME_ALLOW, "127.0.0.1,192.168.0.181");
		/** ip黑名单 黑白名单都存在时，白名单优先级高于黑名单 **/
		statViewServlet.setInitParameter(StatViewServlet.PARAM_NAME_DENY, "192.168.0.100");
		/** 控制台 用户名 **/
		statViewServlet.setInitParameter(StatViewServlet.PARAM_NAME_USERNAME, "yankaiwei");
		/** 控制台 密码 **/
		statViewServlet.setInitParameter(StatViewServlet.PARAM_NAME_PASSWORD, "123456");
		/** 设置是否重置数据 **/
		statViewServlet.setInitParameter(StatViewServlet.PARAM_NAME_RESET_ENABLE, "false");

	}
}
